package com.example.demo.syn;

public class ThreadPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        Producer producer = new Producer(synContainer);
        Consumer consumer = new Consumer(synContainer);
        producer.start();
        consumer.start();
    }
}
class Producer extends Thread{
    SynContainer container;
    Producer(SynContainer container){
        this.container=container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了"+i+"鸡");
        }
    }
}
class Consumer extends Thread{
    SynContainer container;
    Consumer( SynContainer container){
        this.container=container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Chicken pop = container.pop();
            System.out.println("消费了"+pop.id+"鸡");
        }
    }
}
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}
class SynContainer{
    Chicken[] chickens = new Chicken[10];
    //计数器
    int count=0;
    synchronized void  push(Chicken chicken){
        if (count == chickens.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        chickens[count]=chicken;
        count++;
        this.notifyAll();
    }
    synchronized Chicken pop(){
        if (count==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        this.notifyAll();
        return chicken;
    }
}